<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>定/销货单</title>
    <style>
        @media print {
            @page {
                size: A4;
                margin: 0.4in 0.3in 0.2in 0.3in !important;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            body {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
        }
        
        body {
            font-family: "SimSun", "宋体", serif;
            margin: 10px;
            line-height: 1.3;
            color: #000;
            font-size: 12px;
        }
        
        .user-info {
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.9);
            padding: 8px 15px;
            border-radius: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            font-size: 14px;
            z-index: 1000;
        }
        
        .user-info span {
            margin-right: 10px;
            color: #333;
        }
        
        .logout-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 4px 12px;
            border-radius: 12px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .logout-btn:hover {
            background: #c82333;
        }
        
        .action-buttons {
            margin: 20px 0;
            text-align: center;
            gap: 15px;
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s ease;
            color: white;
        }
        
        .btn-save {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .btn-new {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        }
        
        .btn-print {
            background: linear-gradient(135deg, #495057 0%, #6c757d 100%);
        }
        
        .btn-export {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        }
        
        .btn-image {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        
        .header {
            text-align: center;
            margin-bottom: 12px;
            background: #f8f9fa;
            color: #000000;
            padding: 10px;
            border: 1px solid #000000;
            border-radius: 6px;
            position: relative;
        }
        
        .document-type-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            position: relative;
        }
        
        .header h1 {
            font-family: "Microsoft YaHei", "黑体", "SimHei", sans-serif;
            font-size: 28px;
            font-weight: 900;
            margin: 0;
            color: #000000;
            letter-spacing: 2px;
            display: inline-block;
        }
        
        .document-type-display {
            cursor: pointer;
            font-size: 24px;
            font-weight: bold;
            color: #000000;
            user-select: none;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .dropdown-arrow {
            display: none;
        }
        
        .document-type-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border: 2px solid #000000;
            border-radius: 5px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            min-width: 120px;
            display: none;
        }
        
        .dropdown-option {
            padding: 10px 15px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background-color 0.2s ease;
        }
        
        .dropdown-option:hover {
            background-color: #f8f9fa;
        }
        
        .header .order-number {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 16px;
            background: rgba(0,0,0,0.1);
            padding: 8px 15px;
            border-radius: 5px;
        }
        
        .order-number input {
            background: transparent;
            border: none;
            color: #000000;
            font-size: 16px;
            width: 200px;
            outline: none;
            border-bottom: 2px solid rgba(0,0,0,0.5);
            padding: 5px;
        }
        
        .notice {
            font-size: 12px;
            margin-bottom: 10px;
            padding: 8px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            color: #333;
            border-radius: 4px;
            border-left: 3px solid #6c757d;
        }
        
        .notice strong {
            font-size: 16px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 8px;
            border-radius: 4px;
            overflow: hidden;
        }
        
        td, th {
            border: 1px solid #333;
            padding: 6px;
            text-align: left;
            vertical-align: middle;
        }
        
        .info-table td {
            height: 28px;
            font-size: 12px;
        }
        
        .info-table td:first-child {
            background-color: #e9ecef;
            color: #000000;
            font-weight: bold;
            text-align: center;
            border: 1px solid #000000;
        }
        
        .product-table th {
            background: #d6d8db;
            color: #000000;
            text-align: center;
            font-family: "Microsoft YaHei", "黑体", "SimHei", sans-serif;
            font-weight: 900;
            font-size: 14px;
            padding: 12px 8px;
            border: 2px solid #000000;
            letter-spacing: 1px;
        }
        
        .product-table td {
            height: 24px;
            font-size: 12px;
        }
        
        .product-table tfoot td {
            background-color: #d6d8db;
            color: #000000;
            font-weight: bold;
            border: 1px solid #000000;
        }
        
        .payment-section {
            margin-top: 8px;
        }
        
        .payment-table td {
            height: 26px;
            font-size: 12px;
        }
        
        .payment-table td:first-child {
            background-color: #f8f9fa;
            font-weight: bold;
            text-align: center;
        }
        
        .terms {
            margin-top: 10px;
            font-size: 12px;
            padding: 8px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 3px solid #6c757d;
        }
        
        .signature-section {
            margin-top: 10px;
            display: flex;
            justify-content: space-between;
            gap: 10px;
        }
        
        .signature-box {
            flex: 1;
            text-align: center;
            padding: 8px;
            background-color: #f8f9fa;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .signature-line {
            height: 30px;
            border-bottom: 2px solid #333;
            margin: 8px 0;
        }
        
        .signature-stamp {
            height: 30px;
            border: 2px solid #333;
            margin: 8px 0;
            border-radius: 3px;
        }
        
        .agreement {
            font-size: 11px;
            margin-top: 8px;
            padding: 8px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 4px;
            border-left: 3px solid #6c757d;
        }
        
        .input-field {
            width: 100%;
            border: none;
            outline: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            padding: 2px;
        }
        
        .delivery-container {
            height: 100%;
            display: flex;
        }
        
        .delivery-label {
            width: 40%;
            background-color: #f8f9fa;
            font-weight: bold;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            border-right: 1px solid #333;
        }
        
        .delivery-input {
            width: 60%;
            padding: 12px;
            display: flex;
            align-items: center;
        }
        
        .amount-container {
            display: flex;
            height: 100%;
        }
        
        .amount-chinese {
            width: 65%;
            padding: 8px 12px;
            border-right: 1px solid #333;
            display: flex;
            align-items: center;
        }
        
        .amount-number {
            width: 35%;
            padding: 8px 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .negative-warning {
            color: #dc3545 !important;
            font-weight: bold;
        }
        
        @media print {
            @page {
                size: A4;
                margin: 0.4in 0.3in 0.2in 0.3in;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            
            .action-buttons, .user-info {
                display: none !important;
            }
            
            body {
                margin: 0;
                padding: 0;
                background: white;
                font-size: 10px;
                line-height: 1.1;
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
                page-break-inside: avoid;
            }
            
            .header {
                background: #ffffff !important;
                color: #000000 !important;
                padding: 8px !important;
                margin-bottom: 6px !important;
                border: 1px solid #000000 !important;
                page-break-inside: avoid;
                position: relative;
            }
            
            .header .order-number {
                position: absolute !important;
                right: 15px !important;
                top: 50% !important;
                transform: translateY(-50%) !important;
                font-size: 12px !important;
                background: rgba(0,0,0,0.1) !important;
                padding: 4px 8px !important;
                border-radius: 3px !important;
            }
            
            .order-number input {
                width: 150px !important;
                font-size: 12px !important;
                padding: 2px !important;
            }
            
            .document-type-wrapper {
                margin-right: 180px !important;
            }
            
            .notice {
                font-size: 10px !important;
                margin-bottom: 6px !important;
                padding: 6px !important;
                page-break-inside: avoid;
            }
            
            table {
                margin-bottom: 6px !important;
                page-break-inside: avoid;
            }
            
            .info-table td {
                height: 22px !important;
                font-size: 10px !important;
                padding: 4px !important;
            }
            
            .product-table th {
                background: #d6d8db !important;
                color: #000000 !important;
                padding: 8px 4px !important;
                font-size: 11px !important;
                border: 2px solid #000000 !important;
                font-weight: 900 !important;
            }
            
            .product-table td {
                height: 20px !important;
                font-size: 10px !important;
                padding: 3px !important;
            }
            
            .product-table tfoot td {
                background-color: #d6d8db !important;
                color: #000000 !important;
                font-weight: bold !important;
                border: 1px solid #000000 !important;
                padding: 6px !important;
            }
            
            .payment-table td {
                height: 20px !important;
                font-size: 10px !important;
                padding: 4px !important;
            }
            
            .terms {
                font-size: 10px !important;
                margin-top: 6px !important;
                padding: 6px !important;
            }
            
            .signature-section {
                margin-top: 6px !important;
            }
            
            .signature-box {
                padding: 6px !important;
                font-size: 10px !important;
            }
            
            .agreement {
                font-size: 9px !important;
                margin-top: 6px !important;
                padding: 6px !important;
            }
            
            .amount-container {
                height: auto !important;
            }
            
            .amount-chinese, .amount-number {
                padding: 4px 8px !important;
            }
        }
        
        @media screen and (max-width: 768px) {
            .action-buttons {
                flex-direction: column;
                gap: 10px;
            }
            
            .btn {
                width: 100%;
                padding: 14px 20px;
            }
            
            .header .order-number {
                position: static;
                transform: none;
                text-align: center;
                margin-top: 8px;
            }
            
            .user-info {
                position: static;
                margin-bottom: 10px;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="user-info">
        <span id="userDisplay">加载中...</span>
        <button class="logout-btn" onclick="logout()">退出</button>
    </div>

    <div class="action-buttons">
        <button class="btn btn-save" onclick="saveOrder()">💾 保存订单</button>
        <button class="btn btn-new" onclick="createNewOrder()">➕ 保存并新建</button>
        <button class="btn btn-print" onclick="printForm()">🖨️ 打印表单</button>
        <button class="btn btn-export" onclick="exportToPDF()">📄 导出PDF</button>
        <button class="btn btn-image" onclick="exportToImage()">🖼️ 导出图片</button>
        <button class="btn btn-save" onclick="viewHistory()">📋 历史记录</button>
    </div>

    <div class="header">
        <div class="document-type-wrapper">
            <h1>定/销货单</h1>
            <span class="document-type-display" onclick="toggleDocTypeDropdown()">
                <span class="doc-type-text">（预算）</span><span class="dropdown-arrow">▼</span>
            </span>
            <div class="document-type-dropdown" id="docTypeDropdown">
                <div class="dropdown-option" onclick="selectDocType('预算')">（预算）</div>
                <div class="dropdown-option" onclick="selectDocType('结算')">（结算）</div>
            </div>
        </div>
        <div class="order-number">
            单号No.：<input type="text" placeholder="请输入单号" id="orderNumber">
        </div>
    </div>
    
    <div class="notice">
        <strong>温馨提示：</strong>为了购货方的合法权益特制订此政策，请详细阅读本单据购物须知，并确认单据内各项购物内容。一经签字确认，将视同购货方对本单据所有内容均表示同意。
    </div>
    
    <table class="info-table">
        <tr>
            <td style="width: 15%;">购货方</td>
            <td style="width: 35%;"><input type="text" class="input-field" id="buyer"></td>
            <td style="width: 15%;">购货方联系人/电话</td>
            <td style="width: 35%;"><input type="text" class="input-field" id="buyerContact"></td>
        </tr>
        <tr>
            <td>供货方</td>
            <td><input type="text" class="input-field" value="厦门汇仕环保科技有限公司" id="supplier"></td>
            <td>供货方电话</td>
            <td><input type="text" class="input-field" value="0592-5772750" id="supplierPhone"></td>
        </tr>
        <tr>
            <td>供货方地址</td>
            <td colspan="2"><input type="text" class="input-field" value="厦门市湖里区钟宅红星美凯龙E8038" id="supplierAddress"></td>
            <td rowspan="2" style="padding: 0;">
                <div class="delivery-container">
                    <div class="delivery-label">送货方式</div>
                    <div class="delivery-input">
                        <input type="text" class="input-field" list="deliveryList" id="deliveryMethod">
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>收货方地址</td>
            <td colspan="2"><input type="text" class="input-field" id="receiverAddress"></td>
        </tr>
        <tr>
            <td>订货日期</td>
            <td><input type="date" class="input-field" id="orderDate"></td>
            <td>送货时间</td>
            <td><input type="date" class="input-field" id="deliveryDate"></td>
        </tr>
    </table>
    
    <table class="product-table">
        <thead>
            <tr>
                <th style="width: 22%;">商品名称(品牌+名称)</th>
                <th style="width: 10%;">型号</th>
                <th style="width: 10%;">规格</th>
                <th style="width: 10%;">零售价</th>
                <th style="width: 8%;">数量</th>
                <th style="width: 8%;">单位</th>
                <th style="width: 12%;">合价</th>
            </tr>
        </thead>
        <tbody>
            <tr><td><input type="text" class="input-field product-name" list="productList" value="TECH X隔热膜" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" value="晨曦" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec" value="1.52m*30m"></td><td><input type="number" class="input-field product-price" step="0.01" value="799" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
            <tr><td><input type="text" class="input-field product-name" list="productList" onchange="updateProductPrice(this)"></td><td><input type="text" class="input-field product-model" list="modelList" onchange="updateModelPrice(this)"></td><td><input type="text" class="input-field product-spec"></td><td><input type="number" class="input-field product-price" step="0.01" onchange="calculateRow(this)" onblur="formatDecimal(this)"></td><td><input type="number" class="input-field product-quantity" onchange="calculateRow(this)"></td><td><input type="text" class="input-field product-unit" placeholder="㎡"></td><td><input type="number" class="input-field product-total" step="0.01" readonly></td></tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="6" style="text-align: right; padding-right: 10px;">合计：</td>
                <td><input type="number" id="totalAmount" class="input-field" step="0.01" readonly style="font-weight: bold;"></td>
            </tr>
        </tfoot>
    </table>
    
    <table>
        <tr>
            <td style="width: 15%; text-align: center; font-weight: bold; background-color: #f8f9fa;">备注</td>
            <td style="height: 50px;"><input type="text" class="input-field" value="质保期五年，从安装结束之日起算；质保期内非人为和自然灾害原因引起的质量问题、安装问题，由供货方负责维保" id="remarks"></td>
        </tr>
    </table>
    
    <div class="payment-section">
        <table class="payment-table">
            <tr>
                <td style="width: 15%;">付款方式</td>
                <td style="width: 85%;"><input type="text" class="input-field" list="paymentList" id="paymentMethod"></td>
            </tr>
            <tr>
                <td>收款账户</td>
                <td>账号：<input type="text" class="input-field" style="width: 20%; display: inline-block;" value="6226 1529 0065 3167"> 户名：<input type="text" class="input-field" style="width: 15%; display: inline-block;" value="饶玉珍"> 开户行：<input type="text" class="input-field" style="width: 50%; display: inline-block;" value="中国民生银行"></td>
            </tr>
            <tr>
                <td>实售金额</td>
                <td style="padding: 0;">
                    <div class="amount-container">
                        <div class="amount-chinese">
                            <input type="text" class="input-field" placeholder="大写金额" id="totalAmountChinese">
                        </div>
                        <div class="amount-number">
                            小写(¥) <input type="number" class="input-field" style="width: 60%;" step="0.01" id="totalAmountNumber" onchange="updateChinese(this); calculateBalance();" onblur="formatDecimal(this)">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td id="paymentLabel">本次付款金额</td>
                <td style="padding: 0;">
                    <div class="amount-container">
                        <div class="amount-chinese">
                            <input type="text" class="input-field" placeholder="大写金额" id="currentPaymentChinese">
                        </div>
                        <div class="amount-number">
                            小写(¥) <input type="number" class="input-field" style="width: 60%;" step="0.01" id="currentPaymentNumber" onchange="updateChinese(this); calculateBalance();" onblur="formatDecimal(this)">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td>货款余额</td>
                <td style="padding: 0;">
                    <div class="amount-container">
                        <div class="amount-chinese">
                            <input type="text" class="input-field" placeholder="大写金额" id="balanceChinese">
                        </div>
                        <div class="amount-number">
                            小写(¥) <input type="number" class="input-field" style="width: 60%;" step="0.01" id="balanceNumber" readonly>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    
    <div class="terms">
        <strong>其他约定：</strong><br>
        1. 货款余额应由购货方在<input type="text" class="input-field" style="width: 200px; border-bottom: 1px solid #000; display: inline-block;" id="paymentDeadline">付清。<br>
        2. 本单实售合计金额中已包含上门检测、测量、设计、出图等相关费用。
    </div>
    
    <div class="signature-section">
        <div class="signature-box">
            <div>供货方签字：</div>
            <div class="signature-line"></div>
        </div>
        <div class="signature-box">
            <div>售后服务章：</div>
            <div class="signature-stamp"></div>
        </div>
        <div class="signature-box">
            <div>购货方签字：</div>
            <div class="signature-line"></div>
        </div>
    </div>
    
    <div class="agreement">
        <strong>购销约定：</strong>1. 如果已付金额小于合计金额的30%，则以已付金额做为交易定金；如果已付金额大于等于合计金额的30%，则以合计金额的30%做为定金。2. 购货方违约退货的，无权要求返回定金；供货方不能交货的，则应返还定金。
    </div>

    <datalist id="productList">
        <option value="TECH X隔热膜">
        <option value="隔热膜安装费">
    </datalist>
    <datalist id="modelList">
        <option value="晨曦">
        <option value="暮语">
        <option value="智幕Pro70">
        <option value="智幕Pro30">
    </datalist>
    <datalist id="paymentList">
        <option value="对私转账">
        <option value="对公转账">
        <option value="微信转账">
        <option value="现金交付">
    </datalist>
    <datalist id="deliveryList">
        <option value="送货上门">
        <option value="自提">
    </datalist>

    <script>
        // 产品价格映射表
        const productPrices = {
            '晨曦': 799,
            '暮语': 799,
            '智幕Pro70': 1380,
            '智幕Pro30': 1380
        };

        // 人民币大写转换函数
        function numberToChinese(num) {
            if (num === 0 || num === '' || isNaN(num)) return '';
            
            const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
            const units = ['', '拾', '佰', '仟'];
            const bigUnits = ['', '万', '亿'];
            
            let numStr = parseFloat(num).toFixed(2);
            let [integerPart, decimalPart] = numStr.split('.');
            
            let result = '';
            if (integerPart === '0') {
                result = '零';
            } else {
                let intNum = parseInt(integerPart);
                let groups = [];
                
                while (intNum > 0) {
                    groups.push(intNum % 10000);
                    intNum = Math.floor(intNum / 10000);
                }
                
                for (let i = groups.length - 1; i >= 0; i--) {
                    let group = groups[i];
                    if (group === 0) {
                        if (i > 0 && result !== '') result += '零';
                        continue;
                    }
                    
                    let groupStr = '';
                    let tempGroup = group;
                    let unitIndex = 0;
                    let hasZero = false;
                    
                    while (tempGroup > 0) {
                        let digit = tempGroup % 10;
                        if (digit === 0) {
                            if (!hasZero && groupStr !== '') {
                                groupStr = '零' + groupStr;
                                hasZero = true;
                            }
                        } else {
                            groupStr = digits[digit] + units[unitIndex] + groupStr;
                            hasZero = false;
                        }
                        tempGroup = Math.floor(tempGroup / 10);
                        unitIndex++;
                    }
                    
                    if (groupStr.startsWith('零')) {
                        groupStr = groupStr.substring(1);
                    }
                    
                    result += groupStr + bigUnits[i];
                }
            }
            
            result += '元';
            
            if (decimalPart && decimalPart !== '00') {
                let jiao = parseInt(decimalPart[0]);
                let fen = parseInt(decimalPart[1]);
                
                if (jiao > 0) {
                    result += digits[jiao] + '角';
                }
                if (fen > 0) {
                    if (jiao === 0 && result.endsWith('元')) {
                        result += '零';
                    }
                    result += digits[fen] + '分';
                }
            } else {
                result += '整';
            }
            
            return result;
        }

        // 格式化小数点
        function formatDecimal(input) {
            const value = parseFloat(input.value);
            if (!isNaN(value)) {
                input.value = value.toFixed(2);
            }
        }

        // 显示消息提示
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 6px;
                color: white;
                font-size: 14px;
                z-index: 10000;
                opacity: 0;
                transition: all 0.3s ease;
                ${type === 'success' ? 'background: #28a745;' : ''}
                ${type === 'error' ? 'background: #dc3545;' : ''}
                ${type === 'info' ? 'background: #17a2b8;' : ''}
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => toast.style.opacity = '1', 100);
            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    if (toast.parentNode) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }

        // 更新产品价格（根据商品名称）
        function updateProductPrice(input) {
            // 这个函数暂时不做处理，主要通过型号来更新价格
        }

        // 更新型号价格（根据型号）
        function updateModelPrice(input) {
            const modelValue = input.value.trim();
            const row = input.closest('tr');
            const priceInput = row.querySelector('.product-price');
            
            if (productPrices[modelValue]) {
                priceInput.value = productPrices[modelValue].toFixed(2);
                calculateRow(priceInput);
                showToast(`已自动设置${modelValue}的价格：¥${productPrices[modelValue]}`, 'info');
            }
        }

        // 计算行总额
        function calculateRow(input) {
            const row = input.closest('tr');
            const priceInput = row.querySelector('.product-price');
            const quantityInput = row.querySelector('.product-quantity');
            const totalInput = row.querySelector('.product-total');
            
            const price = parseFloat(priceInput.value) || 0;
            const quantity = parseFloat(quantityInput.value) || 0;
            const total = price * quantity;
            
            totalInput.value = total.toFixed(2);
            calculateGrandTotal();
        }

        // 计算总计
        function calculateGrandTotal() {
            const totalInputs = document.querySelectorAll('.product-total');
            let grandTotal = 0;
            
            totalInputs.forEach(input => {
                grandTotal += parseFloat(input.value) || 0;
            });
            
            document.getElementById('totalAmount').value = grandTotal.toFixed(2);
            document.getElementById('totalAmountNumber').value = grandTotal.toFixed(2);
            updateChinese(document.getElementById('totalAmountNumber'));
            calculateBalance();
        }

        // 更新中文大写
        function updateChinese(input) {
            const value = parseFloat(input.value) || 0;
            const chineseValue = numberToChinese(value);
            
            if (input.id === 'totalAmountNumber') {
                document.getElementById('totalAmountChinese').value = chineseValue;
            } else if (input.id === 'currentPaymentNumber') {
                document.getElementById('currentPaymentChinese').value = chineseValue;
            }
        }

        // 计算余额
        function calculateBalance() {
            const total = parseFloat(document.getElementById('totalAmountNumber').value) || 0;
            const payment = parseFloat(document.getElementById('currentPaymentNumber').value) || 0;
            const balance = total - payment;
            
            const balanceInput = document.getElementById('balanceNumber');
            const balanceChineseInput = document.getElementById('balanceChinese');
            
            balanceInput.value = balance.toFixed(2);
            balanceChineseInput.value = numberToChinese(balance);
            
            // 如果余额为负数，显示红色警告
            if (balance < 0) {
                balanceInput.classList.add('negative-warning');
                balanceChineseInput.classList.add('negative-warning');
                showToast('付款金额超过实售金额！', 'error');
            } else {
                balanceInput.classList.remove('negative-warning');
                balanceChineseInput.classList.remove('negative-warning');
            }
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                showToast('已退出登录', 'info');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1000);
            }
        }

        // 保存订单数据（完整版本）
        function saveOrder() {
            try {
                const data = {};
                
                // 保存所有有ID的输入框
                document.querySelectorAll('input[id]').forEach(input => {
                    data[input.id] = input.value;
                });
                
                // 保存产品表格数据
                const productRows = document.querySelectorAll('.product-table tbody tr');
                data.productData = [];
                
                productRows.forEach((row, index) => {
                    const nameInput = row.querySelector('.product-name');
                    const modelInput = row.querySelector('.product-model');
                    const specInput = row.querySelector('.product-spec');
                    const priceInput = row.querySelector('.product-price');
                    const quantityInput = row.querySelector('.product-quantity');
                    const unitInput = row.querySelector('.product-unit');
                    const totalInput = row.querySelector('.product-total');
                    
                    data.productData.push({
                        productName: nameInput ? nameInput.value : '',
                        model: modelInput ? modelInput.value : '',
                        specification: specInput ? specInput.value : '',
                        retailPrice: priceInput ? priceInput.value : '',
                        quantity: quantityInput ? quantityInput.value : '',
                        unit: unitInput ? unitInput.value : '',
                        totalPrice: totalInput ? totalInput.value : ''
                    });
                });
                
                // 保存文档类型
                data.docType = document.querySelector('.doc-type-text').textContent;
                
                // 添加保存时间戳和订单号
                data.saveTime = new Date().toLocaleString('zh-CN');
                data.orderNumber = document.getElementById('orderNumber').value;
                
                console.log('保存的数据:', data);
                
                // 保存到当前数据
                localStorage.setItem('purchaseOrderData', JSON.stringify(data));
                
                // 保存到历史记录
                saveToHistory(data);
                
                showToast('订单保存成功！', 'success');
            } catch (error) {
                console.error('保存失败:', error);
                showToast('保存失败，请重试', 'error');
            }
        }

        // 保存到历史记录
        function saveToHistory(data) {
            try {
                let history = JSON.parse(localStorage.getItem('orderHistory') || '[]');
                
                // 检查是否已存在相同订单号的记录
                const existingIndex = history.findIndex(item => item.orderNumber === data.orderNumber);
                
                if (existingIndex >= 0) {
                    // 更新现有记录
                    history[existingIndex] = data;
                    showToast('订单已更新到历史记录', 'info');
                } else {
                    // 添加新记录
                    history.unshift(data); // 添加到数组开头
                    showToast('订单已添加到历史记录', 'info');
                }
                
                // 限制历史记录数量（最多保存100条）
                if (history.length > 100) {
                    history = history.slice(0, 100);
                }
                
                localStorage.setItem('orderHistory', JSON.stringify(history));
                console.log('历史记录已保存:', history);
            } catch (error) {
                console.error('保存历史记录失败:', error);
            }
        }

        // 从历史记录加载订单数据（完整版本）
        function loadOrderData(data) {
            try {
                console.log('加载的数据:', data);
                
                // 加载所有有ID的输入框
                Object.keys(data).forEach(key => {
                    const input = document.getElementById(key);
                    if (input && key !== 'productData' && key !== 'docType') {
                        input.value = data[key] || '';
                    }
                });
                
                // 加载产品表格数据
                if (data.productData && Array.isArray(data.productData)) {
                    const productRows = document.querySelectorAll('.product-table tbody tr');
                    
                    data.productData.forEach((product, index) => {
                        if (index < productRows.length) {
                            const row = productRows[index];
                            const nameInput = row.querySelector('.product-name');
                            const modelInput = row.querySelector('.product-model');
                            const specInput = row.querySelector('.product-spec');
                            const priceInput = row.querySelector('.product-price');
                            const quantityInput = row.querySelector('.product-quantity');
                            const unitInput = row.querySelector('.product-unit');
                            const totalInput = row.querySelector('.product-total');
                            
                            if (nameInput) nameInput.value = product.productName || '';
                            if (modelInput) modelInput.value = product.model || '';
                            if (specInput) specInput.value = product.specification || '';
                            if (priceInput) priceInput.value = product.retailPrice || '';
                            if (quantityInput) quantityInput.value = product.quantity || '';
                            if (unitInput) unitInput.value = product.unit || '';
                            if (totalInput) totalInput.value = product.totalPrice || '';
                        }
                    });
                }
                
                // 加载文档类型
                if (data.docType) {
                    const docTypeText = document.querySelector('.doc-type-text');
                    if (docTypeText) {
                        docTypeText.textContent = data.docType;
                        
                        // 更新付款标签
                        const paymentLabel = document.getElementById('paymentLabel');
                        if (paymentLabel) {
                            if (data.docType.includes('结算')) {
                                paymentLabel.textContent = '已付款金额';
                            } else {
                                paymentLabel.textContent = '本次付款金额';
                            }
                        }
                    }
                }
                
                // 重新计算总计
                calculateGrandTotal();
                
                showToast('订单数据加载成功！', 'success');
            } catch (error) {
                console.error('加载订单数据失败:', error);
                showToast('加载订单数据失败', 'error');
            }
        }

        // 查看历史记录
        function viewHistory() {
            window.open('history.html', '_blank');
        }

        function createNewOrder() {
            try {
                saveOrder();
                
                // 清空表单（保留供货方信息）
                document.querySelectorAll('.input-field').forEach(input => {
                    if (input.value !== '厦门汇仕环保科技有限公司' && 
                        input.value !== '0592-5772750' && 
                        input.value !== '厦门市湖里区钟宅红星美凯龙E8038' &&
                        input.value !== '质保期五年，从安装结束之日起算；质保期内非人为和自然灾害原因引起的质量问题、安装问题，由供货方负责维保' &&
                        input.value !== '6226 1529 0065 3167' &&
                        input.value !== '饶玉珍' &&
                        input.value !== '中国民生银行') {
                        input.value = '';
                    }
                });
                
                // 生成新订单号
                const now = new Date();
                const orderNumber = 'PO' + now.getFullYear() + 
                                  String(now.getMonth() + 1).padStart(2, '0') + 
                                  String(now.getDate()).padStart(2, '0') + 
                                  String(now.getHours()).padStart(2, '0') + 
                                  String(now.getMinutes()).padStart(2, '0');
                document.getElementById('orderNumber').value = orderNumber;
                
                // 设置今天日期
                const today = new Date().toISOString().split('T')[0];
                document.getElementById('orderDate').value = today;
                document.getElementById('deliveryDate').value = today;
                
                // 重新设置第一行预置数据
                const firstRow = document.querySelector('.product-table tbody tr:first-child');
                if (firstRow) {
                    const nameInput = firstRow.querySelector('.product-name');
                    const modelInput = firstRow.querySelector('.product-model');
                    const specInput = firstRow.querySelector('.product-spec');
                    const priceInput = firstRow.querySelector('.product-price');
                    
                    if (nameInput) nameInput.value = 'TECH X隔热膜';
                    if (modelInput) modelInput.value = '晨曦';
                    if (specInput) specInput.value = '1.52m*30m';
                    if (priceInput) priceInput.value = '799.00';
                }
                
                showToast('新订单创建成功！', 'success');
            } catch (error) {
                console.error('创建新订单失败:', error);
                showToast('创建新订单失败，请重试', 'error');
            }
        }

        function printForm() {
            try {
                window.print();
                showToast('正在打印...', 'info');
            } catch (error) {
                console.error('打印失败:', error);
                showToast('打印失败，请重试', 'error');
            }
        }

        function exportToPDF() {
            try {
                showToast('请在打印对话框中选择"保存为PDF"', 'info');
                setTimeout(() => {
                    window.print();
                }, 1000);
            } catch (error) {
                console.error('导出PDF失败:', error);
                showToast('导出PDF失败，请重试', 'error');
            }
        }

        function exportToImage() {
            try {
                showToast('图片导出功能开发中，请使用打印功能', 'info');
            } catch (error) {
                console.error('导出图片失败:', error);
                showToast('导出图片失败，请重试', 'error');
            }
        }

        // 文档类型切换功能
        function toggleDocTypeDropdown() {
            const dropdown = document.getElementById('docTypeDropdown');
            const arrow = document.querySelector('.dropdown-arrow');
            
            if (dropdown.style.display === 'block') {
                dropdown.style.display = 'none';
                if (arrow) arrow.style.transform = 'rotate(0deg)';
            } else {
                dropdown.style.display = 'block';
                if (arrow) arrow.style.transform = 'rotate(180deg)';
            }
        }
        
        function selectDocType(type) {
            // 保存当前数据（除了单号）
            const currentData = {};
            document.querySelectorAll('input').forEach(input => {
                if (input.id && input.id !== 'orderNumber') {
                    currentData[input.id] = input.value;
                }
            });
            
            // 更新文档类型显示
            document.querySelector('.doc-type-text').textContent = `（${type}）`;
            document.getElementById('docTypeDropdown').style.display = 'none';
            const arrow = document.querySelector('.dropdown-arrow');
            if (arrow) arrow.style.transform = 'rotate(0deg)';
            
            // 更新单号和付款标签
            const orderNumberInput = document.getElementById('orderNumber');
            const paymentLabel = document.getElementById('paymentLabel');
            
            if (type === '结算') {
                // 在单号后添加（结）
                if (orderNumberInput && orderNumberInput.value && !orderNumberInput.value.includes('（结）')) {
                    orderNumberInput.value += '（结）';
                }
                // 更改付款标签
                if (paymentLabel) {
                    paymentLabel.textContent = '已付款金额';
                }
            } else {
                // 移除单号中的（结）
                if (orderNumberInput && orderNumberInput.value) {
                    orderNumberInput.value = orderNumberInput.value.replace('（结）', '');
                }
                // 恢复付款标签
                if (paymentLabel) {
                    paymentLabel.textContent = '本次付款金额';
                }
            }
            
            // 恢复所有数据（不包括单号）
            Object.keys(currentData).forEach(key => {
                const input = document.getElementById(key);
                if (input) {
                    input.value = currentData[key];
                }
            });
            
            showToast(`已切换为${type}模式`, 'info');
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户登录状态
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                showToast('请先登录', 'error');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 2000);
                return;
            }

            // 显示用户信息
            const user = JSON.parse(currentUser);
            document.getElementById('userDisplay').textContent = `欢迎，${user.username}`;

            // 设置默认日期
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('orderDate').value = today;
            document.getElementById('deliveryDate').value = today;
            
            // 生成默认订单号
            const now = new Date();
            const orderNumber = 'PO' + now.getFullYear() + 
                              String(now.getMonth() + 1).padStart(2, '0') + 
                              String(now.getDate()).padStart(2, '0') + 
                              String(now.getHours()).padStart(2, '0') + 
                              String(now.getMinutes()).padStart(2, '0');
            document.getElementById('orderNumber').value = orderNumber;
            
            // 确保预置数据显示
            const firstRow = document.querySelector('.product-table tbody tr:first-child');
            if (firstRow) {
                const nameInput = firstRow.querySelector('.product-name');
                const modelInput = firstRow.querySelector('.product-model');
                const specInput = firstRow.querySelector('.product-spec');
                const priceInput = firstRow.querySelector('.product-price');
                
                if (nameInput) nameInput.value = 'TECH X隔热膜';
                if (modelInput) modelInput.value = '晨曦';
                if (specInput) specInput.value = '1.52m*30m';
                if (priceInput) priceInput.value = '799.00';
            }
            
            // 加载保存的数据
            try {
                const savedData = localStorage.getItem('purchaseOrderData');
                if (savedData) {
                    const data = JSON.parse(savedData);
                    console.log('页面加载时发现保存的数据:', data);
                    loadOrderData(data);
                }
            } catch (error) {
                console.error('加载数据失败:', error);
            }
            
            // 点击其他地方关闭下拉菜单
            document.addEventListener('click', function(event) {
                const wrapper = document.querySelector('.document-type-wrapper');
                if (wrapper && !wrapper.contains(event.target)) {
                    const dropdown = document.getElementById('docTypeDropdown');
                    const arrow = document.querySelector('.dropdown-arrow');
                    if (dropdown) dropdown.style.display = 'none';
                    if (arrow) arrow.style.transform = 'rotate(0deg)';
                }
            });
        });

        // 页面卸载前保存数据
        window.addEventListener('beforeunload', function() {
            try {
                saveOrder();
            } catch (error) {
                console.error('自动保存失败:', error);
            }
        });
    </script>
</body>
</html>